/*
 Copyright 2006-2011 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

package org.bn.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.BitSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bn.types.BitString;

public class BitArrayOutputStream extends BitOutputStream {
    ByteArrayOutputStream baos = null;
    int currentBit = 0;
    
    public BitArrayOutputStream() {
        super(new ByteArrayOutputStream());
        baos = (ByteArrayOutputStream) os;
    }

    public BitArrayOutputStream(int initialSize) {
        super(new ByteArrayOutputStream(initialSize));
        baos = (ByteArrayOutputStream) os;
    }

    @Override
    public void align() {
        try {
            super.align();
        } catch (IOException ex) {
        }
    }

    @Override
    public void writeBit(boolean value) {
        try {
            super.writeBit(value);
        } catch (IOException ex) {}
    }

    @Override
    public void writeBit(int bit) {
        try {
            super.writeBit(bit);
        } catch (IOException ex) { }
    }
    
      
    public void writeTo(OutputStream out) throws IOException {
        flush();
        baos.writeTo(out);
    }
    
    public byte[] toByteArray() {
        byte[] array = baos.toByteArray();
        if (getTrailBitsCnt() > 0)
        {
            array = Arrays.copyOf(array, array.length+1); // +1 for trail bits
            array[array.length-1] = oneOctetBuffer;
        }
        return array;
    }
    
    
    public void reset() {
        align();
        baos.reset();
    }    

    public BitString getBitString() {
        int trailBits = getTrailBitsCnt();
        if (trailBits == 0)
            return new BitString(baos.toByteArray(), trailBits);
        else
        {
            byte[] baosarray = baos.toByteArray();
            byte[] array = new byte[baosarray.length+1]; // +1 for trail bits
            System.arraycopy(baosarray, 0, array, 0, baosarray.length);
            array[array.length-1] = oneOctetBuffer;
            return new BitString(array, trailBits);
        }
    }
}
